# -*- coding: utf-8 -*-
"""
生成hash码
"""
__author__ = "shu2015626"
__date__ = '2018/9/1 15:40'

import random
import hashlib


def hash_code(string, salt='mxshop', algorithm='sha256'):
    """
    记得加盐
    :param string: 要hash的字符串
    :param salt: 对字符串加盐
    :param algorithm: hash算法
    :return:
    """
    if not isinstance(string, bytes):
        string += salt
    else:
        string = string.decode() + salt

    string_bytes = string.encode('utf-8')

    if hasattr(hashlib, algorithm):
        h = getattr(hashlib, algorithm)()
    else:
        raise Exception("不认识的算法，请使用默认算法：%s，或者输入如下内容之一：%s" % (algorithm, "/".join(hashlib.__all__)))

    h.update(string_bytes)
    hash_string = h.hexdigest()
    return hash_string


def generate_code(length=6, schema='number'):
    """
    生成指定长度的验证码
    :param length: 验证码长度
    :param schema: 用于生成验证码的种子字符串包含的元素。可以是number或者en_number
    :return:
    """
    # 指定种子字符串
    number_seeds = '0123456789'
    en_number_seeds = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
    if schema == "number":
        str_seeds = number_seeds
    elif schema == "en_number":
        str_seeds = en_number_seeds
    else:
        str_seeds = en_number_seeds
    # 从种子字符串中随机取出指定长度的字符串
    seeds_length = len(str_seeds) - 1
    string = ''
    for i in range(length):
        string += str_seeds[random.randint(0, seeds_length)]
    return string


if __name__ == "__main__":
    print(generate_code())
    print(generate_code(4))
    print(generate_code(4, 'en_number'))
    print(generate_code(16, 'en_number'))
    print(hash_code("dsfdf"))